package br.gov.frameworkdemoiselle.security.filter.session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.owasp.appsensor.AttackDetectorUtils;
import org.owasp.esapi.ESAPI;


public class CheckCookieListFilter implements Filter {

	Collection<String> expectedCookieNames = new ArrayList<String>();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		String cookieList = filterConfig.getInitParameter("cookieNames");
		
		String safeCookieList = ESAPI.validator().getValidInput("CheckCookieList", cookieList, "CookieListParameters", 1024, false, null);
		
		StringTokenizer st = new StringTokenizer(safeCookieList, ";");
		while (st.hasMoreTokens()) {
			expectedCookieNames.add(st.nextToken());
		}
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		
		AttackDetectorUtils.verifyCookiesPresent((HttpServletRequest) request, expectedCookieNames);
		
		chain.doFilter(request, response);
		
	}

	@Override
	public void destroy() {		
		
	}

}
